package jwt

import (
	"github.com/dgrijalva/jwt-go"
	"time"
)

const SecretKey = "wangweihong.com"

/*
   iss: 签发者
   sub: 面向的用户
   aud: 接收方
   exp: 过期时间
   nbf: 生效时间
   iat: 签发时间
   jti: 唯一身份标识
*/
func GenerateToken(Userid string) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := make(jwt.MapClaims)
	claims["iat"] = time.Now().Unix()                    //签发时间
	claims["exp"] = time.Now().Add(time.Hour * 1).Unix() //过期时间
	claims["UserId"] = Userid
	token.Claims = claims
	return token.SignedString([]byte(SecretKey))
}

func VerifyToken(TokenString string) (string, error) {
	token, err := jwt.Parse(TokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(SecretKey), nil
	})
	if err != nil {
		return "", err
	}
	//取出token中的数据
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims["UserId"].(string), err
	}
	return "", err
}
